package com.toe.sso.utils;
import com.toe.common.pojo.domain.ToeAuthenticationInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 使用securitycontext获取user信息
 */
@Slf4j
public class SecurityContextUtils {

    public static Long getUserInfoId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=null;
        if(authentication instanceof UsernamePasswordAuthenticationToken){
            usernamePasswordAuthenticationToken=(UsernamePasswordAuthenticationToken)authentication;
        }else{
            return null;
        }
        //credentials是security框架中的存在上下文中的用户详情数据
        Object credentials = usernamePasswordAuthenticationToken.getCredentials();
        ToeAuthenticationInfo  authenticationInfo = (ToeAuthenticationInfo) credentials;
        if (authenticationInfo.getUserType().equals("ADMIN")){
            return authenticationInfo.getId();
        }else if (authenticationInfo.getUserType().equals("BUSINESS")){
            return authenticationInfo.getId();
        }else{
            return authenticationInfo.getId();
        }
    }
}
